import { AppRouteRecordRaw } from "@/router/types"
import { getPermMenu } from "@/service/common"
import store from "@/store/index"
import { listToTree } from "@/utils/helper/treeHelper"
import COMPONENT_LAYOUT_DEFAULT from "@/views/common/layout/index.vue"
import { camelCase } from "lodash-es"
import { Action, getModule, Module, Mutation, VuexModule } from "vuex-module-decorators"
import { menuStore } from "./menu"

const NAME = "perms"
@Module({ dynamic: true, namespaced: true, store, name: NAME })
class Perms extends VuexModule {
  private isDynamicAddedRouteState = false

  get getIsDynamicAddedRouteState() {
    return this.isDynamicAddedRouteState
  }

  @Action
  async generateMenusRoutes() {
    //根据用户token获取用户的菜单权限列表
    const listResult = await getPermMenu()
    const { menus, perms } = listResult
    //
    console.log(perms)
    const routeMenus = menus.filter((item: any) => item.type !== 2 && item.is_show)
    menuStore.commitAddMenuTree(
      listToTree(routeMenus, {
        pid: "parent"
      })
    )
    const asyncRoutes = routeMenus.map((item: any) => {
      return {
        icon: item.icon,
        id: item.id,
        path: item.path,
        parent: item.parent,
        meta: {
          keepAlive: item.is_keep_alive,
          title: item.name
        },
        name: item.path === "/" ? "home" : camelCase(item.path.split("/")),
        component: item.view_path
      }
    })

    const routes = getAsyncRoutes(
      listToTree(asyncRoutes, {
        pid: "parent"
      })
    )
    return routes
  }

  @Mutation
  commitDynamicAddedRouteState(added: boolean): void {
    this.isDynamicAddedRouteState = added
  }
}

/**
 * 把后台返回的菜单list组装成routes的要求
 * @param routeList
 */

function getAsyncRoutes(routeList: AppRouteRecordRaw[]) {
  const res: AppRouteRecordRaw[] = []
  const keys = ["path", "name", "children", "redirect", "meta"]
  routeList.forEach(route => {
    const newItem: any = {}
    if (route.component) {
      newItem.component = () => import(`@/${route.component}`)
    } else {
      newItem.component = COMPONENT_LAYOUT_DEFAULT
    }

    for (const key in route) {
      if (keys.includes(key)) {
        newItem[key] = (route as any)[key]
      }
    }
    if (newItem.children && newItem.children.length) {
      newItem.children = getAsyncRoutes(route.children!)
    }
    res.push(newItem)
  })
  return res
}

// function AsyncImportRoute(routes:AppRouteRecordRaw[] | undefined) {
//   if (!routes) return
//   routes.forEach((item:any) => {
//     const { view_path } = item
//   })
// }

// const perms = {
//   state: () => {
//     return {
//       menuTree: []
//     }
//   },
//   action: {
//     generateMenusRoutes({ state, commit, rootState }: any) {
//       console.log({ state, commit, rootState })
//       //  获取后台路由菜单逻辑自行修改
//       // 动态引入组件
//       //  后台路由转菜单结构
//       // 生成路由
//     }
//   }
// }

export { Perms }
export const permStore = getModule<Perms>(Perms)
